package com.daon.common;

import com.daon.pojo.SysLogWithBLOBs;
import com.daon.pojo.SysUser;
import com.daon.service.impl.LogServiceImpl;
import com.daon.util.IpUtil;
import com.daon.util.JsonMapperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @Author 1daon
 * @EMAIL 532418116@qq.com
 * @Version 创建时间：2018/3/14 下午9:39
 * @Modified By 网络请求，请求层捕获
 */
public class HttpInterceptor extends HandlerInterceptorAdapter {

    private static final String START_TIME = "requestStartTime";
    private static final Logger logger = LoggerFactory.getLogger(HttpInterceptor.class);

    /**
     * 实现预处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI().toString();
        Map parameterMap = request.getParameterMap();
        String params = JsonMapperUtil.obj2String(parameterMap);
        SysUser user = (SysUser) request.getSession().getAttribute(Const.CURRENT_USER_INFO);
        if(url.indexOf("/sys") >= 0 && user != null && url.indexOf("login") <= 0) {
            int type = url.endsWith(".do")?2:1;
            Integer uid = user.getUserId();
            String trueName= user.getUserTrueName();
            SysLogWithBLOBs sysLog = new SysLogWithBLOBs();
            sysLog.setLogIp(IpUtil.getRemoteIp(request));
            sysLog.setLogType(type);
            sysLog.setLogUrl(url);
            sysLog.setLogMethod(request.getMethod());
            sysLog.setLogParameter(params);
            sysLog.setLogUserId(uid);
            sysLog.setLogUserName(trueName);
            sysLog.setCreatedAt(new Date());
            LogServiceImpl logService = ApplicationContextHelper.popBean(LogServiceImpl.class);
            logService.add(sysLog);
        }
        logger.info("request start. url:{}, params:{}", url, JsonMapperUtil.obj2String(parameterMap));
        long start = System.currentTimeMillis();
        request.setAttribute(START_TIME, start);
        return true;
    }

    /**
     * 后处理（调用了Service并返回ModelAndView，但未进行页面渲染）
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        String url = request.getRequestURI().toString();
//        long start = (Long) request.getAttribute(START_TIME);
//        long end = System.currentTimeMillis();
//        log.info("request finished. url:{}, cost:{}", url, end - start);
        removeThreadLocalInfo();
    }

    /**
     * 返回处理（已经渲染了页面）
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURI().toString();
        long start = (Long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        logger.info("request completed. url:{}, cost:{}", url, end - start);

        removeThreadLocalInfo();
    }

    public void removeThreadLocalInfo() {
//        RequestHolder.remove();;
    }
}
